<!DOCTYPE html>
<html lang="zh-Hans">
<head>

    <!--[if lt IE 9]>
        <style>body {display: none; background: none !important} </style>
        <meta http-equiv="Refresh" Content="0; url=//outdatedbrowser.com/" />
    <![endif]-->

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta name="format-detection" content="telephone=no" />
<meta name="author" content="王诗翔" />



<meta name="description" content="一些概念这里首先要提及一些概念，然后我们再看具体的实例加以理解。 每一个单独的对象都可以被称为对应类的一个实例（instance）。操作指定类的函数称为方法（method）。 把程序接口从具体的实现细节中分离开来的过程称为封装。 在OOP（面向对象编程）中，我们可以通过一个类创建出另外一个类，只需要指定新类的不同信息即可，这种方法称为继承。由此衍生出，被继承的类称为父类或超类（superclass">
<meta name="keywords" content="R,OOP">
<meta property="og:type" content="article">
<meta property="og:title" content="R-面向对象编程">
<meta property="og:url" content="https://shixiangwang.github.io/2017/09/20/OOPinR/index.html">
<meta property="og:site_name" content="Cloudberry">
<meta property="og:description" content="一些概念这里首先要提及一些概念，然后我们再看具体的实例加以理解。 每一个单独的对象都可以被称为对应类的一个实例（instance）。操作指定类的函数称为方法（method）。 把程序接口从具体的实现细节中分离开来的过程称为封装。 在OOP（面向对象编程）中，我们可以通过一个类创建出另外一个类，只需要指定新类的不同信息即可，这种方法称为继承。由此衍生出，被继承的类称为父类或超类（superclass">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-01-27T04:08:38.410Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="R-面向对象编程">
<meta name="twitter:description" content="一些概念这里首先要提及一些概念，然后我们再看具体的实例加以理解。 每一个单独的对象都可以被称为对应类的一个实例（instance）。操作指定类的函数称为方法（method）。 把程序接口从具体的实现细节中分离开来的过程称为封装。 在OOP（面向对象编程）中，我们可以通过一个类创建出另外一个类，只需要指定新类的不同信息即可，这种方法称为继承。由此衍生出，被继承的类称为父类或超类（superclass">

<link rel="apple-touch-icon" href= "/apple-touch-icon.png">


    <link rel="alternate" href="/atom.xml" title="Cloudberry" type="application/atom+xml">



    <link rel="shortcut icon" href="/favicon.png">



    <link href="//cdn.bootcss.com/animate.css/3.5.1/animate.min.css" rel="stylesheet">



    <link href="//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet">



    <script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
    <link href="//cdn.bootcss.com/pace/1.0.2/themes/blue/pace-theme-minimal.css" rel="stylesheet">


<link rel="stylesheet" href="../../../../css/style.css">



<link href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">


<title>R-面向对象编程 | Cloudberry</title>

<script src="//cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>

<script>
    var yiliaConfig = {
        fancybox: true,
        animate: true,
        isHome: false,
        isPost: true,
        isArchive: false,
        isTag: false,
        isCategory: false,
        fancybox_js: "//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.js",
        scrollreveal: "//cdn.bootcss.com/scrollReveal.js/3.1.4/scrollreveal.min.js",
        search: true
    }
</script>


    <script>
        yiliaConfig.jquery_ui = [true, "//cdn.bootcss.com/jqueryui/1.10.4/jquery-ui.min.js", "//cdn.bootcss.com/jqueryui/1.10.4/css/jquery-ui.min.css"];
    </script>



    <script> yiliaConfig.rootUrl = "\/";</script>






</head>
<body>
  <div id="container">
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
    <header id="header" class="inner">
        <a href="/" class="profilepic">
            <img src="/img/avatar.png" class="animated zoomIn">
        </a>
        <hgroup>
          <h1 class="header-author"><a href="/">王诗翔</a></h1>
        </hgroup>

        
        <p class="header-subtitle">A site for writing life</p>
        

        
            <form id="search-form">
            <input type="text" id="local-search-input" name="q" placeholder="search..." class="search form-control" autocomplete="off" autocorrect="off" searchonload="false" />
            <i class="fa fa-times" onclick="resetSearch()"></i>
            </form>
            <div id="local-search-result"></div>
            <p class='no-result'>No results found <i class='fa fa-spinner fa-pulse'></i></p>
        


        
            <div id="switch-btn" class="switch-btn">
                <div class="icon">
                    <div class="icon-ctn">
                        <div class="icon-wrap icon-house" data-idx="0">
                            <div class="birdhouse"></div>
                            <div class="birdhouse_holes"></div>
                        </div>
                        <div class="icon-wrap icon-ribbon hide" data-idx="1">
                            <div class="ribbon"></div>
                        </div>
                        
                        <div class="icon-wrap icon-link hide" data-idx="2">
                            <div class="loopback_l"></div>
                            <div class="loopback_r"></div>
                        </div>
                        
                        
                        <div class="icon-wrap icon-me hide" data-idx="3">
                            <div class="user"></div>
                            <div class="shoulder"></div>
                        </div>
                        
                    </div>
                    
                </div>
                <div class="tips-box hide">
                    <div class="tips-arrow"></div>
                    <ul class="tips-inner">
                        <li>菜单</li>
                        <li>标签</li>
                        
                        <li>友情链接</li>
                        
                        
                        <li>关于我</li>
                        
                    </ul>
                </div>
            </div>
        

        <div id="switch-area" class="switch-area">
            <div class="switch-wrap">
                <section class="switch-part switch-part1">
                    <nav class="header-menu">
                        <ul>
                        
                            <li><a href="../../../../index.html">主页</a></li>
                        
                            <li><a href="../../../../archives/">所有文章</a></li>
                        
                            <li><a href="../../../../tags/">标签云</a></li>
                        
                            <li><a href="../../../../about/">关于我</a></li>
                        
                        </ul>
                    </nav>
                    <nav class="header-nav">
                        <ul class="social">
                            
                                <a class="fa Email" href="mailto:w_shixiang@163.com" title="Email"></a>
                            
                                <a class="fa GitHub" href="https://github.com/ShixiangWang" title="GitHub"></a>
                            
                                <a class="fa RSS" href="../../../../atom.xml" title="RSS"></a>
                            
                                <a class="fa 知乎" href="https://www.zhihu.com/people/wang-shi-xiang-65/activities" title="知乎"></a>
                            
                                <a class="fa 简书" href="https://www.jianshu.com/u/b6608e27dc74" title="简书"></a>
                            
                                <a class="fa Twitter" href="https://twitter.com/WangShxiang" title="Twitter"></a>
                            
                        </ul>
                    </nav>
                </section>
                
                
                <section class="switch-part switch-part2">
                    <div class="widget tagcloud" id="js-tagcloud">
                        <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Gist/">Gist</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Linux-shell/">Linux shell</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/OOP/">OOP</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/R/">R</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Rmarkdown/">Rmarkdown</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Rmd/">Rmd</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Rstudio/">Rstudio</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/bash-shell/">bash shell</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/fasta/">fasta</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/git/">git</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/github/">github</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/lapply/">lapply</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/linux/">linux</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/markdown/">markdown</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/md/">md</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/python/">python</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/sapply/">sapply</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/sed/">sed</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/shell笔记/">shell笔记</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/survival/">survival</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/survminer/">survminer</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/vapply/">vapply</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/写作/">写作</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/数据处理/">数据处理</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/文本处理/">文本处理</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/生存分析/">生存分析</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/生物信息学/">生物信息学</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/类/">类</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/迭代计算/">迭代计算</a></li></ul>
                    </div>
                </section>
                
                
                
                <section class="switch-part switch-part3">
                    <div id="js-friends">
                    
                      <a class="main-nav-link switch-friends-link" href="http://www.ruanyifeng.com/blog/archives.html">阮一峰的网络日志</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://blog.fens.me/series-r/">R的极客理想系列</a>
                    
                      <a class="main-nav-link switch-friends-link" href="https://yihui.name/">谢益辉</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://www.huangshujia.me/">解螺旋的矿工</a>
                    
                      <a class="main-nav-link switch-friends-link" href="https://github.com/GuangchuangYu">GuangchuangYu</a>
                    
                      <a class="main-nav-link switch-friends-link" href="https://vip.biotrainee.com/">生信技能树</a>
                    
                    </div>
                </section>
                

                
                
                <section class="switch-part switch-part4">
                
                    <div id="js-aboutme">人该是自己生活的主宰，而不是别人手中的行货</div>
                </section>
                
            </div>
        </div>
    </header>                
</div>
    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
      <div class="overlay">
          <div class="slider-trigger"></div>
          <h1 class="header-author js-mobile-header hide"><a href="/" title="回到主页">王诗翔</a></h1>
      </div>
    <div class="intrude-less">
        <header id="header" class="inner">
            <a href="/" class="profilepic">
                <img src="/img/avatar.png" class="animated zoomIn">
            </a>
            <hgroup>
              <h1 class="header-author"><a href="/" title="回到主页">王诗翔</a></h1>
            </hgroup>
            
            <p class="header-subtitle">A site for writing life</p>
            
            <nav class="header-menu">
                <ul>
                
                    <li><a href="../../../../index.html">主页</a></li>
                
                    <li><a href="../../../../archives/">所有文章</a></li>
                
                    <li><a href="../../../../tags/">标签云</a></li>
                
                    <li><a href="../../../../about/">关于我</a></li>
                
                <div class="clearfix"></div>
                </ul>
            </nav>
            <nav class="header-nav">
                        <ul class="social">
                            
                                <a class="fa Email" target="_blank" href="mailto:w_shixiang@163.com" title="Email"></a>
                            
                                <a class="fa GitHub" target="_blank" href="https://github.com/ShixiangWang" title="GitHub"></a>
                            
                                <a class="fa RSS" target="_blank" href="../../../../atom.xml" title="RSS"></a>
                            
                                <a class="fa 知乎" target="_blank" href="https://www.zhihu.com/people/wang-shi-xiang-65/activities" title="知乎"></a>
                            
                                <a class="fa 简书" target="_blank" href="https://www.jianshu.com/u/b6608e27dc74" title="简书"></a>
                            
                                <a class="fa Twitter" target="_blank" href="https://twitter.com/WangShxiang" title="Twitter"></a>
                            
                        </ul>
            </nav>
        </header>                
    </div>
    <link class="menu-list" tags="标签" friends="友情链接" about="关于我"/>
</nav>
      <div class="body-wrap"><article id="post-OOPinR" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="" class="article-date">
      <time datetime="2017-09-19T16:00:00.000Z" itemprop="datePublished">2017-09-20</time>
</a>


    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      R-面向对象编程
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        
    <div class="article-category tagcloud">
    <a class="article-category-link" href="../../../../categories/极客R/">极客R</a><a class="article-category-link" href="../../../../categories/极客R/基本理论/">基本理论</a>
    </div>


        
    <div class="article-tag tagcloud">
        <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../../../tags/OOP/">OOP</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../../../tags/R/">R</a></li></ul>
    </div>

        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
        <h2 id="一些概念"><a href="#一些概念" class="headerlink" title="一些概念"></a>一些概念</h2><p>这里首先要提及一些概念，然后我们再看具体的实例加以理解。</p>
<p>每一个单独的<strong>对象</strong>都可以被称为对应<strong>类</strong>的一个<strong>实例</strong>（instance）。操作指定类的函数称为<strong>方法</strong>（method）。</p>
<p>把程序接口从具体的实现细节中分离开来的过程称为<strong>封装</strong>。</p>
<p>在OOP（面向对象编程）中，我们可以通过一个类创建出另外一个类，只需要指定新类的不同信息即可，这种方法称为<strong>继承</strong>。由此衍生出，被继承的类称为<strong>父类或超类</strong>（superclass），新创建的类称为<strong>子类</strong>（subclass）。</p>
<p>在OOP中，允许同一个方法名操纵不同对象并得到不同的结果，称为<strong>多态</strong>（polymorphism）。</p>
<p>通过一系列的其他类来创建新类的过程称为<strong>组合</strong>（composition）。在一些语言中，一个类可以从多个类中继承方法，称为<strong>多重继承</strong>（multiple inheritance）。</p>
<a id="more"></a>
<h2 id="实例"><a href="#实例" class="headerlink" title="实例"></a>实例</h2><p>大部分其他语言（比如java）的OOP概念都已经包含在R中，但R中具体的语法和结构却有所不同。我们需要通过调用函数<code>setClass</code>来定义一个类，并且需要调用<code>setMethod</code>函数来定义方法。</p>
<p>我们先看一个简单的例子：</p>
<p>我们要实现一个类用来表示时间序列，想定义一个对象包含如下信息：</p>
<ul>
<li>一个数据集合，取自固定周期的时间段</li>
<li>一个开始时间</li>
<li>一个结束时间</li>
<li>时间序列的周期</li>
</ul>
<p>对于可以通过某些属性计算出来的属性信息是多余的。我们从定义一个名为“TimeSeries”的新类开始。</p>
<p><strong>我们将通过一个包含数据、开始时间、结束时间的数值型向量来描述一个时间序列。然后可以通过它们来计算出时间单位、频率和周期。</strong></p>
<p>作为类的使用者，如何展现这些信息并不重要。但是对于类的实现者来说，则非常重要。</p>
<p>R语言中对象存储信息的位置称为<strong>槽</strong>（slot）。我们将该对象需要包含的槽命名为<code>data</code>、<code>start</code>、<code>end</code>。使用<code>setClass</code>函数来创建新类：</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&gt; <span class="keyword">setClass</span>(<span class="string">"TimeSeries"</span>,</span><br><span class="line">+   representation(</span><br><span class="line">+     data=<span class="string">"numeric"</span>,</span><br><span class="line">+     start=<span class="string">"POSIXct"</span>,</span><br><span class="line">+     end=<span class="string">"POSIXct"</span></span><br><span class="line">+     )</span><br><span class="line">+ )</span><br></pre></td></tr></table></figure>
<p><code>representation</code>部分说明了每个槽所包含的R对象的类型。我们使用<code>new</code>函数（针对S4对象的一个泛型<a href="https://baike.baidu.com/item/%E6%9E%84%E9%80%A0%E6%96%B9%E6%B3%95/10455265?fr=aladdin" target="_blank" rel="noopener">构造方法</a>）来新建一个TimeSeries对象。第一个参数名指定类名，其他参数指定槽的值：</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">&gt; my.TimeSeries &lt;- new(<span class="string">"TimeSeries"</span>,</span><br><span class="line">+   data = c(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>),</span><br><span class="line">+   start=as.POSIXct(<span class="string">"07/01/2009 0:00:00"</span>, tz=<span class="string">"GMT"</span>,</span><br><span class="line">+                   format=<span class="string">"%m/%d/%Y %H:%M:%S"</span>),</span><br><span class="line">+   end=as.POSIXct(<span class="string">"07/01/2009 0:05:00"</span>, tz=<span class="string">"GMT"</span>,</span><br><span class="line">+                   format=<span class="string">"%m/%d/%Y %H:%M:%S"</span>)</span><br><span class="line">+ )</span><br><span class="line"></span><br><span class="line">&gt; my.TimeSeries</span><br><span class="line">An object of class <span class="string">"TimeSeries"</span></span><br><span class="line">Slot <span class="string">"data"</span>:</span><br><span class="line">[<span class="number">1</span>] <span class="number">1</span> <span class="number">2</span> <span class="number">3</span> <span class="number">4</span> <span class="number">5</span> <span class="number">6</span></span><br><span class="line"></span><br><span class="line">Slot <span class="string">"start"</span>:</span><br><span class="line">[<span class="number">1</span>] <span class="string">"2009-07-01 GMT"</span></span><br><span class="line"></span><br><span class="line">Slot <span class="string">"end"</span>:</span><br><span class="line">[<span class="number">1</span>] <span class="string">"2009-07-01 00:05:00 GMT"</span></span><br></pre></td></tr></table></figure>
<p><strong>对于一个槽来说，并不是所有的可能值都是有效的。</strong>比如，我们想要确保end发生在start之后，并且两者的长度是1。我们需要编写函数来验证该对象的有效性。R允许自定义函数用来验证特定的类。我们可以通过<code>setValidity</code>函数来设定。</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&gt; setValidity(<span class="string">"TimeSeries"</span>,</span><br><span class="line">+   <span class="keyword">function</span>(object)&#123;</span><br><span class="line">+     object@start &lt;= object@end &amp;&amp;</span><br><span class="line">+     length(object@start) == <span class="number">1</span> &amp;&amp;</span><br><span class="line">+     length(object@end) == <span class="number">1</span></span><br><span class="line">+   &#125;</span><br><span class="line">+ )</span><br><span class="line">Class <span class="string">"TimeSeries"</span> [<span class="keyword">in</span> <span class="string">".GlobalEnv"</span>]</span><br><span class="line"></span><br><span class="line">Slots:</span><br><span class="line"></span><br><span class="line">Name:     data   start     end</span><br><span class="line">Class: numeric POSIXct POSIXct</span><br></pre></td></tr></table></figure>
<p>现在我们可以检查对象在<code>validObject</code>函数下是否有效。</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt; validObject(my.TimeSeries)</span><br><span class="line">[<span class="number">1</span>] <span class="literal">TRUE</span></span><br></pre></td></tr></table></figure>
<p>之后我们新建<code>TimeSeries</code>对象时，R将会自动检查新对象的有效性，并通过抛出错误来拒绝错误的对象。</p>
<p>（也可以在创建类的时候设定验证有效性的方法，详见setClass的完整定义）</p>
<p>定义了类之后，我们来创建新的方法。时间序列有一个属性是周期。我们可以创建一个方法用来提取时间序列中的周期信息。</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&gt; period.TimeSeries &lt;- <span class="keyword">function</span>(object) &#123;</span><br><span class="line">+   <span class="keyword">if</span> (length(object@data) &gt; <span class="number">1</span>) &#123;</span><br><span class="line">+     (object@end - object@start) / (length(object@data) - <span class="number">1</span>)</span><br><span class="line">+   &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">+     <span class="literal">Inf</span></span><br><span class="line">+   &#125;</span><br><span class="line">+ &#125;</span><br></pre></td></tr></table></figure>
<p><strong>假如我们想创建一组函数用来从不同的对象中提取数据序列，而不用考虑对象的类型（即多态）。R提供了一种叫作泛型函数的机制可以实现。</strong>当我们对某个对象调用泛型函数时，R会基于该对象的类找到正确的方法去执行。我们创建一个函数来从泛型对象中提取数据序列：</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt; series &lt;- <span class="keyword">function</span>(object) &#123; object@data &#125;</span><br><span class="line">&gt; <span class="keyword">setGeneric</span>(<span class="string">"series"</span>)</span><br><span class="line">[<span class="number">1</span>] <span class="string">"series"</span></span><br><span class="line">&gt; series(my.TimeSeries)</span><br><span class="line">[<span class="number">1</span>] <span class="number">1</span> <span class="number">2</span> <span class="number">3</span> <span class="number">4</span> <span class="number">5</span> <span class="number">6</span></span><br></pre></td></tr></table></figure>
<p>调用<code>setGeneric</code>可以将<code>series</code>重定义为泛型函数，其默认的方法是旧的<code>series</code>函数的函数体：</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&gt; series</span><br><span class="line">standardGeneric <span class="keyword">for</span> <span class="string">"series"</span> defined from package <span class="string">".GlobalEnv"</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> (object)</span><br><span class="line">standardGeneric(<span class="string">"series"</span>)</span><br><span class="line">&lt;environment: <span class="number">0x205e930</span>&gt;</span><br><span class="line">Methods may be defined <span class="keyword">for</span> arguments: object</span><br><span class="line">Use  showMethods(<span class="string">"series"</span>)  <span class="keyword">for</span> currently available ones.</span><br><span class="line">&gt; showMethods(<span class="string">"series"</span>)</span><br><span class="line">Function: series (package .GlobalEnv)</span><br><span class="line">object=<span class="string">"ANY"</span></span><br><span class="line">object=<span class="string">"TimeSeries"</span></span><br><span class="line">    (inherited from: object=<span class="string">"ANY"</span>)</span><br></pre></td></tr></table></figure>
<p>更进一步地，我们创建一个泛型函数来从对象中提取周期信息，并且特别指定它用来处理我们之前的创建的类。</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&gt; period &lt;- <span class="keyword">function</span>(object) &#123; object@period &#125;</span><br><span class="line">&gt; <span class="keyword">setGeneric</span>(<span class="string">"period"</span>)</span><br><span class="line">[<span class="number">1</span>] <span class="string">"period"</span></span><br><span class="line">&gt; <span class="keyword">setMethod</span>(period, signature=c(<span class="string">"TimeSeries"</span>), definition=period.TimeSeries)</span><br><span class="line">[<span class="number">1</span>] <span class="string">"period"</span></span><br><span class="line">attr(,<span class="string">"package"</span>)</span><br><span class="line">[<span class="number">1</span>] <span class="string">".GlobalEnv"</span></span><br><span class="line">&gt; showMethods(<span class="string">"period"</span>)</span><br><span class="line">Function: period (package .GlobalEnv)</span><br><span class="line">object=<span class="string">"ANY"</span></span><br><span class="line">object=<span class="string">"TimeSeries"</span></span><br></pre></td></tr></table></figure>
<p>调用泛型函数<code>period</code>可以计算<code>TimeSeries</code>对象：</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt; period(my.TimeSeries)</span><br><span class="line">Time difference of <span class="number">1</span> mins</span><br></pre></td></tr></table></figure>
<p>也可以对已存在的泛型函数定义自己的方法，比如为我们创建的类定义一个<code>summary</code>方法：</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&gt; <span class="keyword">setMethod</span>(<span class="string">"summary"</span>,</span><br><span class="line">+    signature=<span class="string">"TimeSeries"</span>,</span><br><span class="line">+    definition=<span class="keyword">function</span>(object) &#123;</span><br><span class="line">+      print(paste(object@start,</span><br><span class="line">+                     <span class="string">" to "</span>,</span><br><span class="line">+                 object@end,</span><br><span class="line">+                 sep=<span class="string">""</span>, collapse=<span class="string">""</span>))</span><br><span class="line">+      print(paste(object@data, sep=<span class="string">""</span>, collapse=<span class="string">","</span>))</span><br><span class="line">+    &#125;</span><br><span class="line">+  )</span><br><span class="line">[<span class="number">1</span>] <span class="string">"summary"</span></span><br><span class="line">&gt; summary(my.TimeSeries)</span><br><span class="line">[<span class="number">1</span>] <span class="string">"2009-07-01 to 2009-07-01 00:05:00"</span></span><br><span class="line">[<span class="number">1</span>] <span class="string">"1,2,3,4,5,6"</span></span><br></pre></td></tr></table></figure>
<p>甚至可以为一个已经存在的操作符定义新的方法：</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">&gt; <span class="keyword">setMethod</span>(<span class="string">"["</span>,</span><br><span class="line">+   signature=c(<span class="string">"TimeSeries"</span>),</span><br><span class="line">+   definition=<span class="keyword">function</span>(x, i, j, <span class="keyword">...</span>, drop) &#123;</span><br><span class="line">+     x@data[i]</span><br><span class="line">+   &#125;</span><br><span class="line">+ )</span><br><span class="line">[<span class="number">1</span>] <span class="string">"["</span></span><br><span class="line">&gt; my.TimeSeries[<span class="number">3</span>]</span><br><span class="line">[<span class="number">1</span>] <span class="number">3</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&gt; my.TimeSeries <span class="comment"># 查看my.TimeSeries对象</span></span><br><span class="line">An object of class <span class="string">"TimeSeries"</span></span><br><span class="line">Slot <span class="string">"data"</span>:</span><br><span class="line">[<span class="number">1</span>] <span class="number">1</span> <span class="number">2</span> <span class="number">3</span> <span class="number">4</span> <span class="number">5</span> <span class="number">6</span></span><br><span class="line"></span><br><span class="line">Slot <span class="string">"start"</span>:</span><br><span class="line">[<span class="number">1</span>] <span class="string">"2009-07-01 GMT"</span></span><br><span class="line"></span><br><span class="line">Slot <span class="string">"end"</span>:</span><br><span class="line">[<span class="number">1</span>] <span class="string">"2009-07-01 00:05:00 GMT"</span></span><br></pre></td></tr></table></figure>
<p>下面演示如何基于<code>TimeSeries</code>类实现一个<code>WeightHistory</code>类以记录个人的历史体重信息。</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">&gt; <span class="keyword">setClass</span>(<span class="string">"TimeSeries"</span>,</span><br><span class="line">+   representation(</span><br><span class="line">+     data=<span class="string">"numeric"</span>,</span><br><span class="line">+     start=<span class="string">"POSIXct"</span>,</span><br><span class="line">+     end=<span class="string">"POSIXct"</span></span><br><span class="line">+</span><br><span class="line">+     )</span><br><span class="line">+ )</span><br><span class="line">&gt; setValidity(<span class="string">"TimeSeries"</span>,</span><br><span class="line">+   <span class="keyword">function</span>(object) &#123;</span><br><span class="line">+     object@start &lt;= object@end &amp;&amp;</span><br><span class="line">+     length(object@start)==<span class="number">1</span> &amp;&amp;</span><br><span class="line">+     length(object@end)==<span class="number">1</span></span><br><span class="line">+   &#125;</span><br><span class="line">+ )</span><br><span class="line">Class <span class="string">"TimeSeries"</span> [<span class="keyword">in</span> <span class="string">".GlobalEnv"</span>]</span><br><span class="line"></span><br><span class="line">Slots:</span><br><span class="line"></span><br><span class="line">Name:     data   start     end</span><br><span class="line">Class: numeric POSIXct POSIXct</span><br></pre></td></tr></table></figure>
<p>创建子类：</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&gt; <span class="keyword">setClass</span>(</span><br><span class="line">+   <span class="string">"WeightHistory"</span>,</span><br><span class="line">+   representation(</span><br><span class="line">+     height = <span class="string">"numeric"</span>,</span><br><span class="line">+     name = <span class="string">"character"</span></span><br><span class="line">+  ),</span><br><span class="line">+   contains = <span class="string">"TimeSeries"</span></span><br><span class="line">+ )</span><br></pre></td></tr></table></figure>
<p>添加实例对象：</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">&gt; john.doe &lt;- new(<span class="string">"WeightHistory"</span>,</span><br><span class="line">+   data=c(<span class="number">170</span>,<span class="number">169</span>,<span class="number">171</span>,<span class="number">168</span>,<span class="number">170</span>,<span class="number">169</span>),</span><br><span class="line">+   start=as.POSIXct(<span class="string">"02/14/2019 0:00:00"</span>, tz=<span class="string">"GMT"</span>,</span><br><span class="line">+     format=<span class="string">"%m/%d/%Y %H:%M:%S"</span>),</span><br><span class="line">+   end=as.POSIXct(<span class="string">"03/28/2019 0:00:00"</span>, tz=<span class="string">"GMT"</span>,</span><br><span class="line">+     format=<span class="string">"%m/%d/%Y %H:%M:%S"</span>),</span><br><span class="line">+   height=<span class="number">72</span>,</span><br><span class="line">+   name=<span class="string">"John Doe"</span>)</span><br><span class="line">&gt; john.doe</span><br><span class="line">An object of class <span class="string">"WeightHistory"</span></span><br><span class="line">Slot <span class="string">"height"</span>:</span><br><span class="line">[<span class="number">1</span>] <span class="number">72</span></span><br><span class="line"></span><br><span class="line">Slot <span class="string">"name"</span>:</span><br><span class="line">[<span class="number">1</span>] <span class="string">"John Doe"</span></span><br><span class="line"></span><br><span class="line">Slot <span class="string">"data"</span>:</span><br><span class="line">[<span class="number">1</span>] <span class="number">170</span> <span class="number">169</span> <span class="number">171</span> <span class="number">168</span> <span class="number">170</span> <span class="number">169</span></span><br><span class="line"></span><br><span class="line">Slot <span class="string">"start"</span>:</span><br><span class="line">[<span class="number">1</span>] <span class="string">"2019-02-14 GMT"</span></span><br><span class="line"></span><br><span class="line">Slot <span class="string">"end"</span>:</span><br><span class="line">[<span class="number">1</span>] <span class="string">"2019-03-28 GMT"</span></span><br></pre></td></tr></table></figure>
<p>我们还可以通过另外一种方式构建一个体重记录。假设我们已经创建好了一个包含人名和体重的<code>Person</code>类。</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt; <span class="keyword">setClass</span>(<span class="string">"Person"</span>,</span><br><span class="line">+   representation(</span><br><span class="line">+     height = <span class="string">"numeric"</span>,</span><br><span class="line">+     name = <span class="string">"character"</span>)</span><br><span class="line">+ )</span><br></pre></td></tr></table></figure>
<p>我们可以创建一个基于<code>TimeSeries</code>类和<code>Person</code>类的体重记录类。</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; <span class="keyword">setClass</span>(</span><br><span class="line">+   <span class="string">"AltWeightHistory"</span>,</span><br><span class="line">+   contains = c(<span class="string">"TimeSeries"</span>, <span class="string">"Person"</span>)</span><br><span class="line">+ )</span><br></pre></td></tr></table></figure>
<p>可以发现，如果我们已经有了先期的开发经验或者相关类的代码，对新任务进行重构是非常方便的。短短几行代码就搞定了，充分利用了代码的可重复性。这也是OOP在高级语言中如此普遍的一个原因吧。</p>
<h2 id="S4类"><a href="#S4类" class="headerlink" title="S4类"></a>S4类</h2><p>我们接下来更深入地探讨构造类的函数。</p>
<h3 id="类的定义"><a href="#类的定义" class="headerlink" title="类的定义"></a>类的定义</h3><p>R中使用<code>setClass</code>函数来创建一个新类，格式如下：</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">setClass</span>(Class, representation, prototype, contains=character(), validity, access, where, version, sealed, package, S3methods=<span class="literal">FALSE</span>)</span><br></pre></td></tr></table></figure>
<p>描述</p>
<ul>
<li>Class - 字符串，用来指定新类的名字（这是唯一必需的参数）</li>
<li>representation - 列表，列表的每一个元素代表不同的槽的类型，元素名为槽名（可以用”ANY”来指定类型为任意）</li>
<li>prototype - 包含各个槽的默认值的对象</li>
<li>contains - 字符向量，包含该类继承的父类名</li>
<li>validity - 验证该类的对象有效性的函数（默认没有检查），可以后续使用<code>setValidity</code>函数来设置</li>
<li>access - 无作用，为了和S-PLUS兼容</li>
<li>where - 存储该对象定义的环境</li>
<li>version - 无作用，为了和S-PLUS兼容</li>
<li>sealed - 逻辑值，表示该类是否还能被setClass按照原来的类名重新定义</li>
<li>package - 字符串，指定该类所在的R包名</li>
<li>S3methods - 逻辑值，表示是否使用了S3类写这个类</li>
</ul>
<p>为了简化类的创建，<code>methods</code>包提供了<code>representation</code>以及<code>protype</code>函数。它们在将其他类继承为数据部分、拥有多个父类、或者组合继承类和槽的时候非常有用。</p>
<p>值得注意的是，有些名字是属性的保留字因而不能作为槽名使用，包括”class”,”comment”,”dim”,”dimnames”,”names”,”rownames”和”tsp”。</p>
<p>可以使用<code>setIs</code>函数来显式地定义继承关系。</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">setIs(class1, class2, test=<span class="literal">NULL</span>, coerce=<span class="literal">NULL</span>, replace=<span class="literal">NULL</span>,</span><br><span class="line">     by=character(), where=topenv(parent.frame()), classDef=, extensionObject=<span class="literal">NULL</span>, doComplete=<span class="literal">TRUE</span>)</span><br></pre></td></tr></table></figure>
<p>可以使用<code>setValidity</code>函数来显式地设置类的验证函数：</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">setValidity(Class, method, where=topenv(parent.frame()))</span><br></pre></td></tr></table></figure>
<p>R可以定义一个虚类作为多个其他类的父类。如果一个虚类本身不包含任何数据，但是如果你想要创建一批函数用于一批类中，这种方式非常有用。可以通过<code>setClassUnion</code>函数实现：</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">setClassUnion(name, members, where)</span><br></pre></td></tr></table></figure>
<ul>
<li>name - 新的父类的名字</li>
<li>members - 字符向量，指定所有子类的名字</li>
<li>where - 新类所在的环境</li>
</ul>
<h3 id="对象的新建"><a href="#对象的新建" class="headerlink" title="对象的新建"></a>对象的新建</h3><p>我们可以通过调用类的<code>new</code>方法新建一个对象。专业术语中称为构造函数。</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">new(c, <span class="keyword">...</span>)</span><br></pre></td></tr></table></figure>
<p>在调用<code>new</code>的时候，我们可以通过指定参数将数据填充到槽中。如果<code>c</code>中存在名为<code>initialize</code>的方法，那么当新的对象被创建后，会立刻调用<code>initialize</code>函数进行初始化。</p>
<h3 id="槽的存取"><a href="#槽的存取" class="headerlink" title="槽的存取"></a>槽的存取</h3><p>我们可以使用<code>slot</code>函数或者简化符号<code>@</code>来访问存储对象某个槽中的值，当然也可以用它来赋值。</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; john.doe@name</span><br><span class="line">[<span class="number">1</span>] <span class="string">"John Doe"</span></span><br><span class="line">&gt; slot(john.doe, <span class="string">"name"</span>)</span><br><span class="line">[<span class="number">1</span>] <span class="string">"John Doe"</span></span><br></pre></td></tr></table></figure>
<h3 id="对象的操作"><a href="#对象的操作" class="headerlink" title="对象的操作"></a>对象的操作</h3><p>使用<code>is(o, c)</code>函数测试对象<code>o</code>是否是类<code>c</code>的成员。使用函数<code>extend(c1, c2)</code>测试类<code>c1</code>是否继承于类<code>c2</code>。</p>
<p>如果要得到对象<code>o</code>包含的所有槽的名称，使用<code>slotNames(o)</code>，如果要得到槽的类型，使用<code>getSlots(o)</code>。这两个函数也可以对类使用。</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&gt; getSlots(<span class="string">"WeightHistory"</span>)</span><br><span class="line">     height        name        data       start         end</span><br><span class="line">  <span class="string">"numeric"</span> <span class="string">"character"</span>   <span class="string">"numeric"</span>   <span class="string">"POSIXct"</span>   <span class="string">"POSIXct"</span></span><br><span class="line"></span><br><span class="line">&gt; slotNames(<span class="string">"WeightHistory"</span>)</span><br><span class="line">[<span class="number">1</span>] <span class="string">"height"</span> <span class="string">"name"</span>   <span class="string">"data"</span>   <span class="string">"start"</span>  <span class="string">"end"</span></span><br><span class="line">&gt; slotNames(<span class="string">"john.doe"</span>)</span><br><span class="line">character(<span class="number">0</span>)</span><br><span class="line">&gt; slotNames(john.doe)</span><br><span class="line">[<span class="number">1</span>] <span class="string">"height"</span> <span class="string">"name"</span>   <span class="string">"data"</span>   <span class="string">"start"</span>  <span class="string">"end"</span></span><br></pre></td></tr></table></figure>
<p>注意一些差别，有引号和没引号结果是不同的。</p>
<h3 id="方法"><a href="#方法" class="headerlink" title="方法"></a>方法</h3><p>泛型函数允许使用同一个函数名来代表很多不同的函数，针对不同的类，调用不同的参数。</p>
<p>设定方法的第一步是创建一个合适的泛型函数，如果该函数还不存在，可以使用<code>setGeneric</code>函数来创建这个泛型方法：</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">setGeneric</span>(name, def=, group=list(), valueClass=character(),</span><br><span class="line">          where=, package=, signature=, useAsDefault=,</span><br><span class="line">          genericFUnction=, simpleInheritanceOnly=)</span><br></pre></td></tr></table></figure>
<p>要把一个方法关联到某个类（具体而言就是指定泛型函数的signature参数），可以使用<code>setMethod</code>函数：</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">setMethod</span>(f, signature=character(), definition,</span><br><span class="line">         where = topenv(parent.frame()),</span><br><span class="line">         valueClass=<span class="literal">NULL</span>, sealed=<span class="literal">FALSE</span>)</span><br></pre></td></tr></table></figure>
<h4 id="方法的管理"><a href="#方法的管理" class="headerlink" title="方法的管理"></a>方法的管理</h4><p><code>methods</code>包包含了很多管理泛型方法的函数。</p>
<table>
<thead>
<tr>
<th>函数</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>isGeneric</td>
<td>检查指定的泛型函数是否存在</td>
</tr>
<tr>
<td>isGroup</td>
<td>检查指定的分组泛型函数是否存在</td>
</tr>
<tr>
<td>removeGeneric</td>
<td>删除某个泛型函数关联的所有方法以及该泛型函数本身</td>
</tr>
<tr>
<td>dumpMethod</td>
<td>转存储某个方法到文件</td>
</tr>
<tr>
<td>findFunction</td>
<td>根据函数名查找函数对象，返回搜寻列表中的位置或当前顶层环境</td>
</tr>
<tr>
<td>dumpMethods</td>
<td>转存储一个泛型函数关联的所有方法</td>
</tr>
<tr>
<td>signature</td>
<td>返回在某个指定路径下定义了方法的泛型函数的名称</td>
</tr>
<tr>
<td>removeMethods</td>
<td>删除某个泛型函数关联的所有方法</td>
</tr>
<tr>
<td>setGeneric</td>
<td>根据指定的函数名创建新的泛型函数</td>
</tr>
</tbody>
</table>
<p><code>methods</code>包同样包含了很多管理方法的函数。</p>
<table>
<thead>
<tr>
<th>函数</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>getMethod, selectMethod</td>
<td>返回某个特定泛型函数和类型标记的方法</td>
</tr>
<tr>
<td>existsMethod, hasMethod</td>
<td>检查某个方法（指定了泛型函数名和类型标记）是否存在</td>
</tr>
<tr>
<td>findMethod</td>
<td>返回包含了某个方法的包</td>
</tr>
<tr>
<td>showMethods</td>
<td>显示关联了某个S4泛型的所有方法</td>
</tr>
</tbody>
</table>
<p>更多的帮助通过<code>library(help=&quot;methods&quot;)</code>命令获取。</p>
<h2 id="守旧派OOP-S3"><a href="#守旧派OOP-S3" class="headerlink" title="守旧派OOP: S3"></a>守旧派OOP: S3</h2><p>如果我们想要用R实现复杂的工程，应该使用S4的类和对象。不幸的是，我们在R中是很难避免S3对象的。比如统计包中的大部分建模工具都是用S3对象实现的。为了能够对这些软件包进行更好地理解、修改和扩展。我们必须了解S3类是如何实现的。</p>
<h3 id="S3的类"><a href="#S3的类" class="headerlink" title="S3的类"></a>S3的类</h3><p>S3对象只是原始的R对象加上一些额外的属性（包括一个类名）而已。它没有正式的定义，我们可以手工修改属性甚至类。</p>
<p>之前我们使用了时间序列作为S4的例子，其实在R中已经存在了表示它的S3类，称为<code>ts</code>对象。我们这里创建简单的时间序列对象，查看它的属性以及一些底层对象。</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">&gt; my.ts &lt;- ts(data=c(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>), start=c(<span class="number">2009</span>,<span class="number">2</span>), frequency=<span class="number">12</span>)</span><br><span class="line">&gt; my.ts</span><br><span class="line">     Feb Mar Apr May Jun</span><br><span class="line"><span class="number">2009</span>   <span class="number">1</span>   <span class="number">2</span>   <span class="number">3</span>   <span class="number">4</span>   <span class="number">5</span></span><br><span class="line">&gt; attributes(my.ts)</span><br><span class="line">$tsp</span><br><span class="line">[<span class="number">1</span>] <span class="number">2009.083</span> <span class="number">2009.417</span>   <span class="number">12.000</span></span><br><span class="line"></span><br><span class="line">$class</span><br><span class="line">[<span class="number">1</span>] <span class="string">"ts"</span></span><br><span class="line"></span><br><span class="line">&gt; typeof(my.ts)</span><br><span class="line">[<span class="number">1</span>] <span class="string">"double"</span></span><br><span class="line">&gt; unclass(my.ts)</span><br><span class="line">[<span class="number">1</span>] <span class="number">1</span> <span class="number">2</span> <span class="number">3</span> <span class="number">4</span> <span class="number">5</span></span><br><span class="line">attr(,<span class="string">"tsp"</span>)</span><br><span class="line">[<span class="number">1</span>] <span class="number">2009.083</span> <span class="number">2009.417</span>   <span class="number">12.000</span></span><br><span class="line">&gt; attributes(my.ts)</span><br><span class="line">$tsp</span><br><span class="line">[<span class="number">1</span>] <span class="number">2009.083</span> <span class="number">2009.417</span>   <span class="number">12.000</span></span><br><span class="line"></span><br><span class="line">$class</span><br><span class="line">[<span class="number">1</span>] <span class="string">"ts"</span></span><br></pre></td></tr></table></figure>
<p>可以发现<code>ts</code>对象只不过是一个数值向量加上<code>class</code>和<code>tsp</code>这两个属性。<code>class</code>属性起始只是<code>ts</code>对象的类名。我们无法像S4对象中操作槽来提取S3对象的属性。</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt; my.ts@tsp</span><br><span class="line">错误: 非S4类别的对象(类别为<span class="string">"ts"</span>)没有<span class="string">"tsp"</span>这样的槽</span><br></pre></td></tr></table></figure>
<h3 id="S3方法"><a href="#S3方法" class="headerlink" title="S3方法"></a>S3方法</h3><p>S3的泛型函数是通过命名约定来实现的。以下是步骤：</p>
<ol>
<li>为泛型函数挑选一个名字，这里我们命名为<code>gname</code>。</li>
<li>新建一个名为<code>gname</code>的函数，在<code>gname</code>的函数体中，调用<code>UseMethod(&quot;gname&quot;)</code></li>
<li>为每一个想要使用<code>gname</code>的类创建一个名为<code>gname.classname</code>的函数，该函数的第一个参数必须是该对象的类名<code>classname</code>。</li>
</ol>
<p>一个现成的例子是<code>plot</code>函数：</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt; plot</span><br><span class="line"><span class="keyword">function</span> (x, y, <span class="keyword">...</span>)</span><br><span class="line">UseMethod(<span class="string">"plot"</span>)</span><br><span class="line">&lt;bytecode: <span class="number">0x1851c30</span>&gt;</span><br><span class="line">&lt;environment: namespace:graphics&gt;</span><br></pre></td></tr></table></figure>
<p>在调用<code>plot</code>的时候，<code>plot</code>将会调用<code>UseMethod(&quot;plot&quot;)</code>。<code>UseMethod</code>会查看<code>x</code>对象的类，然后查找名为<code>plot.class</code>的函数，然后调用该函数。</p>
<p>比如给我们之前定义的<code>TimeSeries</code>类添加一个<code>plot</code>方法。</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt; plot.TimeSeries &lt;- <span class="keyword">function</span>(object, <span class="keyword">...</span>) &#123;</span><br><span class="line">+   plot(object@data, <span class="keyword">...</span>)</span><br><span class="line">+ &#125;</span><br></pre></td></tr></table></figure>
<h3 id="在S4的类中使用S3的类"><a href="#在S4的类中使用S3的类" class="headerlink" title="在S4的类中使用S3的类"></a>在S4的类中使用S3的类</h3><p>我们不能直接指定S3的类到S4的槽。如果想要做到，我们需要基于S3的类创建一个S4的类。一个简单的方式是使用<code>setOldClass</code>函数：</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">setOldClass(Classes, prototype, where, test=<span class="literal">FALSE</span>, S4Class)</span><br></pre></td></tr></table></figure>
<h3 id="查找隐藏的S3方法"><a href="#查找隐藏的S3方法" class="headerlink" title="查找隐藏的S3方法"></a>查找隐藏的S3方法</h3><p>有时候我们会发现一些包的作者会选择隐藏单个方法，而把方法的实现封装在包中。这样可以鼓励用户去使用泛型函数。</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; <span class="keyword">library</span>(lattice)</span><br><span class="line">&gt; methods(histogram)</span><br><span class="line">[<span class="number">1</span>] histogram.factor*  histogram.formula* histogram.numeric*</span><br><span class="line">see <span class="string">'?methods'</span> <span class="keyword">for</span> accessing help and <span class="keyword">source</span> code</span><br></pre></td></tr></table></figure>
<p>有时候我们可能需要找回这些隐藏的方法（想要查看源代码），这时候可以使用<code>getS3method</code>函数。例如，想要取到<code>histgram.formula</code>中的代码，可以使用以下命令：</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt; getS3method(f=<span class="string">"histogram"</span>, class=<span class="string">"formula"</span>)</span><br></pre></td></tr></table></figure>
<p>或者使用<code>getAnywhere</code>函数：</p>
<figure class="highlight r"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt; getAnywhere(histogram.formula)</span><br></pre></td></tr></table></figure>
<hr>
<p>学习整理自《R核心技术手册》</p>

      
    </div>
    
  </div>
  
    
    <div class="copyright">
        <p><span>本文标题:</span><a href="">R-面向对象编程</a></p>
        <!-- modify author information
        <p><span>文章作者:</span><a href="/" title="回到主页">王诗翔</a></p>
        -->
        <p><span>文章作者:</span>王诗翔</p>
        <p><span>发布时间:</span>2017-09-20, 00:00:00</p>
        <p><span>最后更新:</span>2018-01-27, 12:08:38</p>
        <p>
            <span>原始链接:</span><a class="post-url" href="" title="R-面向对象编程">https://shixiangwang.github.io/2017/09/20/OOPinR/</a>
            <span class="copy-path" data-clipboard-text="原文: https://shixiangwang.github.io/2017/09/20/OOPinR/　　作者: 王诗翔" title="点击复制文章链接"><i class="fa fa-clipboard"></i></span>
            <script> var clipboard = new Clipboard('.copy-path'); </script>
        </p>
        <p>
            <span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/" title="CC BY-NC-SA 4.0 International" target = "_blank">"署名-非商用-相同方式共享 4.0"</a> 转载请保留原文链接及作者。
        </p>
    </div>



    <nav id="article-nav">
        
            <div id="article-nav-newer" class="article-nav-title">
                <a href="../../../11/26/shell-create-function/">
                    创建和使用shell函数
                </a>
            </div>
        
        
            <div id="article-nav-older" class="article-nav-title">
                <a href="../../15/Class-in-R/">
                    R中的属性与类
                </a>
            </div>
        
    </nav>


  
</article>

    <div id="toc" class="toc-article">
        <strong class="toc-title">文章目录</strong>
        
            <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一些概念"><span class="toc-number">1.</span> <span class="toc-text">一些概念</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#实例"><span class="toc-number">2.</span> <span class="toc-text">实例</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#S4类"><span class="toc-number">3.</span> <span class="toc-text">S4类</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#类的定义"><span class="toc-number">3.1.</span> <span class="toc-text">类的定义</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#对象的新建"><span class="toc-number">3.2.</span> <span class="toc-text">对象的新建</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#槽的存取"><span class="toc-number">3.3.</span> <span class="toc-text">槽的存取</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#对象的操作"><span class="toc-number">3.4.</span> <span class="toc-text">对象的操作</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#方法"><span class="toc-number">3.5.</span> <span class="toc-text">方法</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#方法的管理"><span class="toc-number">3.5.1.</span> <span class="toc-text">方法的管理</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#守旧派OOP-S3"><span class="toc-number">4.</span> <span class="toc-text">守旧派OOP: S3</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#S3的类"><span class="toc-number">4.1.</span> <span class="toc-text">S3的类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#S3方法"><span class="toc-number">4.2.</span> <span class="toc-text">S3方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#在S4的类中使用S3的类"><span class="toc-number">4.3.</span> <span class="toc-text">在S4的类中使用S3的类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#查找隐藏的S3方法"><span class="toc-number">4.4.</span> <span class="toc-text">查找隐藏的S3方法</span></a></li></ol></li></ol>
        
    </div>
    <style>
        .left-col .switch-btn,
        .left-col .switch-area {
            display: none;
        }
        .toc-level-3 i,
        .toc-level-3 ol {
            display: none !important;
        }
    </style>

    <input type="button" id="tocButton" value="隐藏目录"  title="点击按钮隐藏或者显示文章目录">

    <script>
        yiliaConfig.toc = ["隐藏目录", "显示目录", !!"false"];
    </script>



    
<div class="share">
    
        <div class="bdsharebuttonbox">
            <a href="#" class="fa fa-twitter bds_twi" data-cmd="twi" title="分享到推特"></a>
            <a href="#" class="fa fa-weibo bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
            <a href="#" class="fa fa-qq bds_sqq" data-cmd="sqq" title="分享给 QQ 好友"></a>
            <a href="#" class="fa fa-files-o bds_copy" data-cmd="copy" title="复制网址"></a>
            <a href="#" class="fa fa fa-envelope-o bds_mail" data-cmd="mail" title="通过邮件分享"></a>
            <a href="#" class="fa fa-weixin bds_weixin" data-cmd="weixin" title="生成文章二维码"></a>
            <a href="#" class="fa fa-share-alt bds_more" data-cmd="more"></i></a>
        </div>
        <script>
            window._bd_share_config={
                "common":{"bdSnsKey":{},"bdText":"R-面向对象编程　| Cloudberry　","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"24"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
        </script>
    

    
</div>







    
        <section id="comments">
    <style> aside.comment-bar { margin: auto 30px; }</style>
    <div id="disqus_thread"></div>
    <script>
        var disqus_config = function(){
            this.page.url = 'https://shixiangwang.github.io/2017/09/20/OOPinR/';
            this.page.identifier = '2017/09/20/OOPinR/';
        };
        var loadComment = function(){
            var d = document, s = d.createElement('script');
            s.src = '//Cloudberry.disqus.com/embed.js';
            s.setAttribute('data-timestamp', +new Date());
            (d.head || d.body).appendChild(s);
        }
    </script>
    
    <script> loadComment(); </script>

</section>


    




    <div class="scroll" id="post-nav-button">
        
            <a href="../../../11/26/shell-create-function/" title="上一篇: 创建和使用shell函数">
                <i class="fa fa-angle-left"></i>
            </a>
        

        <a title="文章列表"><i class="fa fa-bars"></i><i class="fa fa-times"></i></a>

        
            <a href="../../15/Class-in-R/" title="下一篇: R中的属性与类">
                <i class="fa fa-angle-right"></i>
            </a>
        
    </div>

    <ul class="post-list"><li class="post-list-item"><a class="post-list-link" href="../../../../2018/02/26/python-basics/">两天研习Python基础</a></li><li class="post-list-item"><a class="post-list-link" href="../../../../2018/02/12/how-to-create-an-independent-figpath/">为markdown博文创建独立图片路径</a></li><li class="post-list-item"><a class="post-list-link" href="../../../../2018/02/10/easy-sapply-apply-vapply/">简单理解lapply,sapply,vapply</a></li><li class="post-list-item"><a class="post-list-link" href="../../../../2018/02/07/how-to-do-group-survival-analysis/">怎么对连续变量分组并进行生存分析</a></li><li class="post-list-item"><a class="post-list-link" href="../../../../2018/02/06/how-to-write-rmd-documents-in-hexo-system/">怎么在hexo博客系统中用Rmarkdown写文章</a></li><li class="post-list-item"><a class="post-list-link" href="../../../../2018/01/31/sed-how-to-filter-rows-before-using-command/">sed如何在执行命令前过滤特定文本行</a></li><li class="post-list-item"><a class="post-list-link" href="../../../../2018/01/31/sync-deploy-tools/">Sync deploy 命令工具</a></li><li class="post-list-item"><a class="post-list-link" href="../../../12/25/sed-and-gawk/">初识sed与awk</a></li><li class="post-list-item"><a class="post-list-link" href="../../../12/08/Git-basic-operation/">学习git</a></li><li class="post-list-item"><a class="post-list-link" href="../../../11/29/shell-create-text-menu-and-window/">使用shell创建文本菜单和窗口部件</a></li><li class="post-list-item"><a class="post-list-link" href="../../../11/26/shell-create-function/">创建和使用shell函数</a></li><li class="post-list-item"><a class="post-list-link" href="">R-面向对象编程</a></li><li class="post-list-item"><a class="post-list-link" href="../../15/Class-in-R/">R中的属性与类</a></li><li class="post-list-item"><a class="post-list-link" href="../../04/control_shell/">控制脚本</a></li><li class="post-list-item"><a class="post-list-link" href="../../03/Linux-data-analysis-tools/">Linux数据处理命令工具</a></li><li class="post-list-item"><a class="post-list-link" href="../../../08/21/shell-show-data/">Linux脚本编程——呈现数据</a></li><li class="post-list-item"><a class="post-list-link" href="../../../08/19/working-with-user-input/">Shell脚本之处理用户输入</a></li><li class="post-list-item"><a class="post-list-link" href="../../../08/11/structural-command-of-shell/">Linux结构化命令</a></li><li class="post-list-item"><a class="post-list-link" href="../../../08/11/basic-shell/">构建基本shell脚本</a></li></ul>




    <script>
        
    </script>
</div>
      <footer id="footer">
    <div class="outer">
        <div id="footer-info">
            <div class="footer-left">
                <i class="fa fa-copyright"></i> 
                2017-2018 王诗翔
            </div>
            <div class="footer-right">
                <a href="http://hexo.io/" target="_blank" title="快速、简洁且高效的博客框架">Hexo</a>  Theme <a href="https://github.com/MOxFIVE/hexo-theme-yelee" target="_blank" title="简而不减 Hexo 双栏博客主题  v3.5">Yelee</a> by MOxFIVE <i class="fa fa-heart animated infinite pulse"></i>
            </div>
        </div>
        
            <div class="visit">
                
                    <span id="busuanzi_container_site_pv" style='display:none'>
                        <span id="site-visit" title="本站到访数"><i class="fa fa-user" aria-hidden="true"></i><span id="busuanzi_value_site_uv"></span>
                        </span>
                    </span>
                
                
                    <span>| </span>
                
                
                    <span id="busuanzi_container_page_pv" style='display:none'>
                        <span id="page-visit"  title="本页阅读量"><i class="fa fa-eye animated infinite pulse" aria-hidden="true"></i><span id="busuanzi_value_page_pv"></span>
                        </span>
                    </span>
                
            </div>
        
    </div>
</footer>
    </div>
    
    <script src="../../../../js/GithubRepoWidget.js"></script>

<script data-main="/js/main.js" src="//cdn.bootcss.com/require.js/2.2.0/require.min.js"></script>

    <script>
        $(document).ready(function() {
            var iPad = window.navigator.userAgent.indexOf('iPad');
            if (iPad > -1 || $(".left-col").css("display") === "none") {
                var bgColorList = ["#9db3f4", "#414141", "#e5a859", "#f5dfc6", "#c084a0", "#847e72", "#cd8390", "#996731"];
                var bgColor = Math.ceil(Math.random() * (bgColorList.length - 1));
                $("body").css({"background-color": bgColorList[bgColor], "background-size": "cover"});
            }
            else {
                var backgroundnum = 2;
                var backgroundimg = "url(/background/bg-x.jpg)".replace(/x/gi, Math.ceil(Math.random() * backgroundnum));
                $("body").css({"background": backgroundimg, "background-attachment": "fixed", "background-size": "cover"});
            }
        })
    </script>





    <script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script src="//cdn.bootcss.com/mathjax/2.6.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


<div class="scroll" id="scroll">
    <a href="#" title="返回顶部"><i class="fa fa-arrow-up"></i></a>
    <a href="#comments" onclick="load$hide();" title="查看评论"><i class="fa fa-comments-o"></i></a>
    <a href="#footer" title="转到底部"><i class="fa fa-arrow-down"></i></a>
</div>
<script>
    // Open in New Window
    
        var oOpenInNew = {
             github: ".github-widget a", 
            
             post: ".article-entry a[href], .copyright a[href]", 
            
            
            
             archives: ".archive-article-title", 
             miniArchives: "a.post-list-link", 
            
             friends: "#js-friends a", 
             socail: ".social a" 
        }
        for (var x in oOpenInNew) {
            $(oOpenInNew[x]).attr("target", "_blank");
        }
    
</script>

    <script>
        var originTitle = document.title;
        var titleTime;
        document.addEventListener("visibilitychange", function() {
            if (document.hidden) {
                document.title = "(つェ⊂) 我藏好了哦~ " + originTitle;
                clearTimeout(titleTime);
            }
            else {
                document.title = "(*´∇｀*) 被你发现啦~ " + originTitle;
                titleTime = setTimeout(function() {
                    document.title = originTitle;
                }, 2000);
            }
        })
    </script>

<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  </div>
</body>
</html>